import json
import os
import requests
from typing import Dict, Any
import time

# TransBridge API configuration
TRANSBRIDGE_API_URL = "https://freeapi.fanyimao.cn/translate"
TRANSBRIDGE_TOKEN = "tr-98584e33-f387-42cc-a467-f02513bd400d"

def translate_text(text: str) -> str:
    """Translate text from Chinese to English using TransBridge API."""
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {TRANSBRIDGE_TOKEN}"
    }
    
    data = {
        "text": text,
        "source_lang": "zh",
        "target_lang": "en"
    }
    
    max_retries = 3
    for attempt in range(max_retries):
        try:
            response = requests.post(TRANSBRIDGE_API_URL, headers=headers, json=data)
            response.raise_for_status()
            result = response.json()
            
            # Add a delay to avoid rate limiting
            time.sleep(1.5)
            
            if isinstance(result, dict):
                if "data" in result and isinstance(result["data"], str):
                    translated = result["data"]
                    print(f"Translated: '{text}' -> '{translated}'")
                    return translated
            
            print(f"Unexpected response format for text '{text}': {result}")
            return text
                
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                print(f"Error translating text '{text}' after {max_retries} attempts: {str(e)}")
                return text
            time.sleep(2 ** attempt)  # Exponential backoff
            continue
        except Exception as e:
            print(f"Error translating text '{text}': {str(e)}")
            return text

def translate_value(value: Any) -> Any:
    """Recursively translate string values in data structure."""
    if isinstance(value, str) and value.strip():  # Only translate non-empty strings
        return translate_text(value)
    elif isinstance(value, dict):
        return {k: translate_value(v) for k, v in value.items()}
    elif isinstance(value, list):
        return [translate_value(item) for item in value]
    return value

def process_json_file(input_path: str, output_path: str):
    """Process a single JSON file."""
    try:
        print(f"\nProcessing {input_path}...")
        with open(input_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # Translate the content
        translated_data = translate_value(data)
        
        # Save translated content
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(translated_data, f, ensure_ascii=False, indent=2)
            
        print(f"Successfully translated {input_path} to {output_path}")
    except Exception as e:
        print(f"Error processing file {input_path}: {str(e)}")

def main():
    input_dir = "miss/zh-Hant"
    output_dir = "miss/en-machine"
    
    # Create output directory if it doesn't exist
    os.makedirs(output_dir, exist_ok=True)
    
    # Process all JSON files
    for filename in os.listdir(input_dir):
        if filename.endswith('.json'):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            process_json_file(input_path, output_path)

if __name__ == "__main__":
    main() 